package com.zzh.order.service.impl;

import com.netflix.appinfo.InstanceInfo;
import com.zzh.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    private AtomicInteger reqCount  = new AtomicInteger(1);

    /**
     * 自己实现本地负载均衡
     * @return
     */
    @Override
    public String getOrder() {
        List<ServiceInstance> instancesById = discoveryClient.getInstances("sc-member");
        if(null==instancesById){
            return "";
        }
        int ServiceCount = instancesById.size();
        int index = reqCount.get()%ServiceCount;
        reqCount.getAndIncrement();
        return restTemplate.getForObject(instancesById.get(index).getUri()+"/getMember",String.class);
    }
}
